package com.bjpowernode.security03json.config;

import com.bjpowernode.security03json.handler.AppAccessDeniedHandler;
import com.bjpowernode.security03json.handler.AppAuthenticationFailureHandler;
import com.bjpowernode.security03json.handler.AppAuthenticationSuccessHandler;
import com.bjpowernode.security03json.handler.AppLogoutSuccessHandler;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * security配置类
 */
@Configuration
public class MySecurityConfiguration {

    @Resource
    private AppAccessDeniedHandler appAccessDeniedHandler;

    @Resource
    private AppAuthenticationFailureHandler appAuthenticationFailureHandler;

    @Resource
    private AppAuthenticationSuccessHandler appAuthenticationSuccessHandler;

    @Resource
    private AppLogoutSuccessHandler appLogoutSuccessHandler;

    /**
     * 编写security的配置
     * @param httpSecurity
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //security6之前的写法
        //httpSecurity.exceptionHandling().accessDeniedHandler(appAccessDeniedHandler);

        //配置没有权限的handler
        httpSecurity.exceptionHandling(handler -> handler.accessDeniedHandler(appAccessDeniedHandler));

       //配置认证成功和失败的handler
        httpSecurity.formLogin(handler -> handler
                .successHandler(appAuthenticationSuccessHandler)
                .failureHandler(appAuthenticationFailureHandler));

        //配置退出的handler
        httpSecurity.logout(handler -> handler.logoutSuccessHandler(appLogoutSuccessHandler));


        return httpSecurity.build();
    }
}
